package com.lyj.service.impl;

import java.util.List;

import com.lyj.dao.UserDao;
import com.lyj.dao.impl.UserDaoImpl;
import com.lyj.pojo.User;
import com.lyj.pojo.UserQueryModel;
import com.lyj.service.UserService;
import com.lyj.util.RuleException;
import com.lyj.util.format.MD5Class;


/**
* 处理用户数据的业务逻辑类
* @author 李艺江
* @version 创建时间：2018年12月4日 下午4:27:23
*/

public class UserServiceImpl implements UserService{
	//业务逻辑依赖于数据访问
	private UserDao userDao;
	public UserServiceImpl(){
		userDao = new UserDaoImpl();
	}
	
	
	@Override
	public void register(User user) throws Exception {
		//因为用户操作不当违反业务规则，		
		if(user.getName() == null || user.getName().trim().length()==0){
			//抛出异常
			throw new RuleException("用户名不能为空");
		}
		//....
		if(user.getPwd() == null || user.getPwd().trim().length() == 0) {
			throw new RuleException("密码不能为空");
		}
		
		if(user.getConfirmPwd() == null || user.getConfirmPwd().trim().length() == 0) {
			throw new RuleException("确认密码不能为空");
		}
		
		if(!user.getPwd().equals(user.getConfirmPwd())){
			throw new RuleException("确认密码和密码不一致");
		}
		
		//用户名不能重复
		UserQueryModel qm = new UserQueryModel();
		qm.setName(user.getName());
		List list = userDao.findByCondition(qm);
		if(list.size()>0){
			throw new RuleException("用户名已经被注册");
		}
		
		user.setOnline(1);
		user.setPwd(MD5Class.stringToMd5(user.getPwd()));
		
		userDao.insert(user);
	}
	
	public User login(User user)  throws Exception{
		
		if(user.getName() == null || user.getName().trim().length()==0){
			//抛出异常
			throw new RuleException("用户名不能为空");
		}
		
	
		if(user.getPwd() == null || user.getPwd().trim().length() == 0) {
			throw new RuleException("密码不能为空");
		}
		

		UserQueryModel qm = new UserQueryModel();
		qm.setName(user.getName());
		qm.setPwd(MD5Class.stringToMd5(user.getPwd()));
		
		List list = userDao.findByCondition(qm);
		if(list.size() == 1) {
			user = (User) list.get(0);
			//检查在线状态
			if(user.getOnline() == User.ONLINE) {
				throw new RuleException("该用户已经登录!");
			}
			
			//修改在线状态为已在线
			user.setOnline(User.ONLINE);
			userDao.update(user);
			
		}else {
			throw new RuleException("用户名不存在或密码错误!");
		}
		return user;
	}


	@Override
	public User getUser(int id) throws Exception {
		User user = (User) userDao.findOne(id);
		return user;
	}


	@Override
	public void online(User user, boolean inOrOut) {
		try {
			if(inOrOut){
				user.setOnline(2);
			}
			else{
			    user.setOnline(1);
			}
			
			userDao.update(user);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}	
	}
}
